﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using CCWin;
using CCWin.SkinControl;
using System.Runtime.InteropServices;
using CCWin.Win32;
using GroupChat2013.Common;
using GroupChat2013.Entity;
using GroupChat2013.Main.Properties;
using GroupChat2013.Logic;
using GroupChat2013.Plugins;
using GroupChat2013.Logic.Interface;
using GroupChat2013.Data;
using GroupChat2013.Service;
using System.IO;
using System.Web;

namespace GroupChat2013.Main
{
    public partial class FrmMain : CCSkinMain
    {
        #region 变量

        /// <summary>
        /// 当前登录用户
        /// </summary>
        public UserInfo m_CurrentUser
        {
            get { return EngineContext.Current.CurrUserInfo; }
        }

        //变量
        private int form_top_old;
        private int form_left_old;
        private int form_right_old;
        private int SW;
        private int SH;

        private ChatListItem groupItem;

        /// <summary>
        /// 重启贴边隐藏的timer
        /// </summary>
        private System.Windows.Forms.Timer reSetTimHideStart = new System.Windows.Forms.Timer();

        /// <summary>
        /// 通知栏
        /// </summary>
        private AnnounceConfigInfo m_AnnounceConfigInfo { get; set; }

        #endregion

        #region 自定义事件

        /// <summary>
        /// 窗体加载完成
        /// </summary>
        public event Action CompletedHandle;

        /// <summary>
        /// 程序退出事件
        /// </summary>
        public event Action ExistedHandle;

        #endregion

        #region 构造函数

        public FrmMain()
        {
            FrmMain.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();

            //获取屏幕宽高
            SW = Screen.PrimaryScreen.Bounds.Width;
            SH = Screen.PrimaryScreen.Bounds.Height;

            reSetTimHideStart.Interval = 1500;
            reSetTimHideStart.Tick += new EventHandler(reSetTimHideStart_Tick);
            this.lblQm.Click += new EventHandler(lblQm_Click);
        }

        #endregion

        #region 初始化加载逻辑

        //窗口加载时
        private void FormMain_Load(object sender, EventArgs e)
        {
            string temp = string.Empty;
            //获取屏幕宽高与调节最大大小
            this.MaximumSize = new Size(543, Screen.GetWorkingArea(this).Height);

            ChatShow.Visible = true;
            GroupShow.Visible = false;
            RecentShow.Visible = false;

            tsmGroupManager.Visible = tsmGroupManager2.Visible = EngineContext.Current.CurrUserInfo.groupAdmin;

            if (this.CompletedHandle != null)
            {
                this.CompletedHandle();
            }

            //主面板具体左边的距离
            this.Left = SW - (int)(this.Width * 1.2);
            AddPlugins();

            //通知栏
            InitAnnounce();

            InitGroupMenu();

            lblName.Text = m_CurrentUser.UserName;

            //点击树节点动态加载数据
            ChatShow.ClickTreeNode += (s, ex) => { ClickTreeNode(ex.CliceOnTreeItem); };
        }

        /// <summary>
        /// 初始化主面板的tab
        /// </summary>
        public void InitMainTab(TabConfigInfo tabConfigInfo)
        {
            this.skinToolStrip3.Items.Clear();
            //主面板显示“群”、“组织机构”、“最近联系人”
            if (tabConfigInfo.showTab == ConstClass.RTXPlugin)
            {
                //初始化群列表
                InitGroupList();

                //组织架构
                InitStructure();

                //加载最近联系人
                LoadRecChat();

                this.skinToolStrip3.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                this.toolStripBtnGroup,
                this.toolStripBtnFriend,                
                this.toolStripBtnRecently});

                //txtSearch.WaterText = "搜索: 组织机构、群";
                toolStripBtnGroup_ButtonClick(toolStripBtnGroup, null);
            }
            //主面板显示“组织机构”、“群”、“最近联系人”
            else if (tabConfigInfo.showTab == ConstClass.IsAlone)
            {
                //组织架构
                InitStructure();

                //初始化群列表
                InitGroupList();

                //加载最近联系人
                LoadRecChat();

                this.skinToolStrip3.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                this.toolStripBtnFriend,
                this.toolStripBtnGroup,                                
                this.toolStripBtnRecently});

                //txtSearch.WaterText = "搜索: 组织机构、群";
                toolStripBtnFriend_ButtonClick(toolStripBtnFriend, null);
            }
            //主面板只显示“群”和“最近联系人”
            else if (tabConfigInfo.showTab == ConstClass.SimpleRTXPlugin)
            {
                //初始化群列表
                InitGroupList();

                //加载最近联系人
                LoadRecChat();

                this.skinToolStrip3.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                this.toolStripBtnGroup,                                
                this.toolStripBtnRecently});

                toolStripBtnGroup_ButtonClick(toolStripBtnGroup, null);

                //txtSearch.WaterText = "搜索: 群";
            }
        }

        /// <summary>
        /// 初始化组织架构
        /// </summary>
        private void InitStructure()
        {
            OrganizeInfo organizeInfo = ServiceUrlProxy.GetInstance().GetOrganizeRootNode(m_CurrentUser.CID);
            if (organizeInfo == null || organizeInfo.deptNodes == null || organizeInfo.deptNodes.Count == 0)
            {
                ChatTreeItem root = new ChatTreeItem("未获取到组织架构");
                root.IsOpen = false;
                ChatShow.Items.Add(root);
                return;
            }
            else
            {
                foreach (OrganizeNode node in organizeInfo.deptNodes)
                {
                    ChatTreeItem root = new ChatTreeItem(node.dept.deptName);
                    root.Data = node;
                    root.IsOpen = true;
                    ChatShow.Items.Add(root);

                    root.IsRequestOK = true;
                    root.IsRequesting = false;
                    ClickTreeNode(root);
                }
            }
            //ChatTreeItem root = new ChatTreeItem("中国招商银行");
            //root.IsOpen = true;
            //ChatShow.Items.Add(root);

            //ChatTreeItem root2 = new ChatTreeItem("中国发展银行");
            //ChatShow.Items.Add(root2);
            //Random rnd = new Random();

            //for (int i = 1; i <= 3; i++)
            //{
            //    ChatTreeItem item = new ChatTreeItem(i + "级公司的节点");
            //    item.IsOpen = false;
            //    root.Items.Add(item);

            //    for (int k = 1; k <= 3; k++)
            //    {
            //        ChatTreeItem itemk = new ChatTreeItem(i + "-" + k + "级公司的节点");
            //        itemk.IsOpen = false;
            //        item.Items.Add(itemk);

            //        for (int l = 1; l <= 3; l++)
            //        {
            //            ChatTreeItem iteml = new ChatTreeItem(i + "-" + k + "-" + l + "级公司的节点");
            //            iteml.IsOpen = false;
            //            itemk.Items.Add(iteml);

            //            for (int m = 1; m <= 2; m++)
            //            {
            //                ChatTreeItem itemm = new ChatTreeItem(i + "-" + k + "-" + "-" + l + "-" + m + "级公司的节点");
            //                itemm.IsOpen = false;
            //                iteml.Items.Add(itemm);

            //                for (int j = 0; j < 2; j++)
            //                {
            //                    ChatTreeSubItem subItem = new ChatTreeSubItem(j.ToString(), "NicName" + j, i + "-" + k + "-" + "-" + l + "-" + m + "-" + j + "级好友", string.Empty, ChatType.User);
            //                    subItem.HeadImage = Image.FromFile("head/" + 1 + ".png");
            //                    subItem.ID = ((1 + 1) * (j + 1)).ToString();
            //                    subItem.Status = (ChatTreeSubItem.UserStatus)(j % 6);
            //                    subItem.ChatType = ChatType.User;
            //                    itemm.SubItems.AddAccordingToStatus(subItem);
            //                }
            //            }
            //        }
            //    }
            //}
        }

        /// <summary>
        /// 初始化群列表
        /// </summary>
        public void InitGroupList()
        {
            groupItem = new ChatListItem("我的群");
            groupItem.IsOpen = true;
            GroupShow.Items.Add(groupItem);

            try
            {
                AsyncClient.AsyncCall<List<GroupInfo>>(() =>
                {
                    return ServiceUrlProxy.GetInstance().GetGroupList(m_CurrentUser.CID);
                },
                (groupList) =>
                {
                    if (groupList != null && groupList.Count > 0)
                    {
                        GroupNotifyRepository groupNotify = new GroupNotifyRepository(EngineContext.Current.FilePathManager.DbPath);
                        List<string> groupIdList = groupNotify.GetBubbleNotifyGroups();

                        foreach (GroupInfo group in groupList)
                        {
                            ChatListSubItem subItem = new ChatListSubItem();
                            subItem.HeadImage = Image.FromFile(GroupChat2013.Common.Helper.CombinePath(@"head\group.PNG"));
                            subItem.ID = group.groupId;
                            subItem.DisplayName = group.groupName;
                            subItem.NicName = group.groupName;
                            subItem.PersonalMsg = group.groupDesc;
                            subItem.ChatType = ChatType.Group;

                            if (groupIdList.Exists(x => { return x == subItem.ID; }))
                            {
                                subItem.IsBubbleNotify = true;
                            }

                            groupItem.SubItems.AddAccordingToStatus(subItem);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                LogHelper.LogError(string.Format("InitGroupList()方法 错误信息：{0} 堆栈信息：{1} ", ex.Message, ex.StackTrace));
            }
        }

        /// <summary>
        /// 加载最近联系人
        /// </summary>
        private void LoadRecChat()
        {
            ChatListItem recentItem = new ChatListItem("最近联系人");
            recentItem.IsOpen = true;
            RecentShow.Items.Add(recentItem);

            List<RecChatInfo> recChatList = new List<RecChatInfo>();
            RecChatRepository chatRepository = new RecChatRepository(EngineContext.Current.FilePathManager.DbPath);
            recChatList = chatRepository.GetRecChatInfos(ConstClass.LoadRecChatCount);
            recChatList.ForEach(x =>
            {
                ChatListSubItem subItem = new ChatListSubItem(x.ChatId, x.NickName, x.ChatName, "", x.ChatType);
                if (x.ChatType == ChatType.Group)
                {
                    subItem.HeadImage = Image.FromFile(GroupChat2013.Common.Helper.CombinePath(@"head\group.PNG"));
                }
                else
                {
                    subItem.HeadImage = Image.FromFile(GroupChat2013.Common.Helper.CombinePath(@"head\1.png"));
                }
                //subItem.Status = (ChatListSubItem.UserStatus)(j % 6);
                recentItem.SubItems.Add(subItem);
            });
        }

        /// <summary>
        /// 初始化面板上下按钮
        /// </summary>
        /// <param name="buttonConfigList"></param>
        public void InitMainButton(List<ButtonConfigInfo> buttonConfigList)
        {
            List<ButtonConfigInfo> buttons = null;
            List<ToolStripItem> items = new List<ToolStripItem>();
            this.skinToolBusBtn.Items.Clear();

            int maxCount = 8;

            //上部按钮设置
            buttons = buttonConfigList.FindAll(x => { return x.pos == ConstClass.UpButtonPostion; });
            if (buttons != null && buttons.Count > 0)
            {
                int widthup = this.skinToolBusBtn.Width;
                int itemWidth = widthup / maxCount;

                items.Clear();
                for (int i = 0; i < buttons.Count; i++)
                {
                    //string name = "tsButtonUP" + i;
                    items.Add(CreateToolStripButton(buttons[i], buttons[i].name));
                }

                widthup = buttons.Count > maxCount ? widthup : itemWidth * buttons.Count;

                this.skinToolBusBtn.Items.AddRange(items.ToArray());
                this.skinToolBusBtn.Width = widthup;
            }

            //下部按钮设置
            buttons = buttonConfigList.FindAll(x => { return x.pos == ConstClass.DownButtonPostion; });
            if (buttons != null && buttons.Count > 0)
            {
                int widthdown = this.SkToolCdTwo.Width - toolQQMenu.Width;
                int itemWidth = widthdown / maxCount - 1;

                items.Clear();
                for (int i = 0; i < buttons.Count; i++)
                {
                    //string name = "tsButtonDown" + i;
                    items.Add(CreateToolStripButton(buttons[i], buttons[i].name));
                }

                widthdown = toolQQMenu.Width + (buttons.Count > maxCount - 1 ? widthdown : itemWidth * buttons.Count + 1);

                this.SkToolCdTwo.Items.AddRange(items.ToArray());
                this.SkToolCdTwo.Width = widthdown;
            }
        }

        /// <summary>
        /// 创建按钮
        /// </summary>
        /// <param name="configInfo"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private ToolStripButton CreateToolStripButton(ButtonConfigInfo configInfo, string name)
        {
            ToolStripButton button = new ToolStripButton();
            button.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;

            if (name == ConstClass.appUnRead)
            {
                button.Image = Resources.messagebox1;
            }
            else
            {
                button.Image = string.IsNullOrEmpty(configInfo.imgNormal) ? (Image)Resources.default_ButtonImg : Image.FromFile(configInfo.imgNormal);
            }

            button.ImageTransparentColor = System.Drawing.Color.Magenta;
            button.Name = name;
            button.Size = new System.Drawing.Size(23, 21);
            button.Text = configInfo.desc;
            button.ToolTipText = configInfo.tip;
            button.Tag = configInfo;

            button.Click += (s, e) =>
            {
                string url = GroupChat2013.Common.Helper.AddUrlParams(configInfo.link, "cid=" + EngineContext.Current.CurrUserInfo.CID);
                FrmGroup.OpenWithChrome(url);

                if (name == ConstClass.appUnRead)
                {
                    button.Image = Resources.messagebox1;
                    skinToolBusBtn.Update();
                }
            };

            return button;
        }

        /// <summary>
        /// 添加插件到主面板
        /// </summary>
        public void AddPlugins()
        {
            if (EngineContext.Current.Plugins == null)
                return;

            int index = 0;
            int width = this.skinToolStrip1.Width;
            int maxCount = 8;
            int itemWidth = width / maxCount;

            foreach (IPlugin plug in EngineContext.Current.Plugins)
            {
                IPlugin p = plug;
                ToolStripButton toolButton = new ToolStripButton();
                toolButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
                toolButton.Image = plug.IconImage;
                toolButton.ImageTransparentColor = System.Drawing.Color.Magenta;
                toolButton.Name = "toolStripButton" + index;
                toolButton.Text = plug.Description;
                toolButton.Size = new System.Drawing.Size(23, 21);
                toolButton.Click += (s, e) =>
                {
                    p.Execute(EngineContext.Current.PluginContext);
                };
                skinToolStrip1.Items.Add(toolButton);
                index++;
            }

            width = EngineContext.Current.Plugins.Count > maxCount ? width : itemWidth * EngineContext.Current.Plugins.Count;
            skinToolStrip1.Width = width;
        }

        /// <summary>
        /// 初始化通知栏
        /// </summary>
        public void InitAnnounce()
        {
            AsyncClient.AsyncCall<AnnounceConfigInfo>(() =>
            {
                return ServiceUrlProxy.GetInstance().GetAnnounceConfig();
            },
            (announceConfigInfo) =>
            {
                ParseConfig<AnnounceConfigInfo> parseConfig = new ParseConfig<AnnounceConfigInfo>(EngineContext.Current.FilePathManager.PersonConfigPath,
                    ConstClass.AnnounceConfig,
                    () => { return new AnnounceConfigInfo(); });

                if (announceConfigInfo != null)
                {
                    m_AnnounceConfigInfo = announceConfigInfo;
                    parseConfig.SaveConfig(announceConfigInfo);
                }
                else
                {
                    m_AnnounceConfigInfo = parseConfig.Parse();
                }

                this.BeginInvoke(new Action(() =>
                {
                    //设置通知栏信息
                    lblQm.Text = m_AnnounceConfigInfo.showAnnounce;
                }));
            });
        }

        #endregion

        #region 计时器贴边隐藏

        //贴边隐藏
        int? hg = null;
        private void timHide_Tick(object sender, EventArgs e)
        {
            //隐藏窗口的方法
            form_top_old = 2 - this.Height;
            form_left_old = 2 - this.Width;
            form_right_old = SW - 2;
            //没点击移动时
            if (!this.isMouseDown)
            {
                //鼠标在窗体内时
                if (this.Bounds.Contains(Cursor.Position))
                {
                    ShowPanelWhenHide();
                }
                else
                {
                    switch (this.Aanhor)
                    {
                        //执行左移特效
                        case AnchorStyles.Left:
                            if (this.Left != form_left_old)
                            {
                                for (int i = 0; i >= form_left_old; i -= 15)
                                {
                                    this.Left = i;
                                }
                                this.Left = form_left_old;
                            }
                            break;
                        //执行右移特效
                        case AnchorStyles.Right:
                            if (this.Left != form_right_old)
                            {
                                for (int i = SW - this.Width; i <= form_right_old; i += 15)
                                {
                                    this.Left = i;
                                }
                                this.Left = form_right_old;
                            }
                            break;
                        //执行上移特效
                        case AnchorStyles.Top:
                            if (this.Top != form_top_old)
                            {
                                for (int i = 0; i >= form_top_old; i -= 15)
                                {
                                    this.Top = i;
                                }
                                this.Top = form_top_old;
                            }
                            break;
                    }
                }
            }
        }

        private void reSetTimHideStart_Tick(object sender, EventArgs e)
        {
            timHide.Start();
            reSetTimHideStart.Stop();
        }

        public new void Show()
        {
            base.Show();
            this.WindowState = FormWindowState.Normal;
            WinAPI.SetActiveWindow(this.Handle);

            timHide.Stop();
            ShowPanelWhenHide();

            reSetTimHideStart.Start();
        }

        public void ShowPanelWhenHide()
        {
            switch (this.Aanhor)
            {
                //执行右移特效
                case AnchorStyles.Left:
                    if (hg == null)
                    {
                        hg = this.Height;
                    }
                    this.Height = MaximumSize.Height;
                    this.Top = 0;
                    int b = this.Left;
                    for (int i = b; i < 0; i += 15)
                    {
                        this.Left = i;
                    }
                    this.Left = 0;
                    break;
                //执行左移特效
                case AnchorStyles.Right:
                    if (hg == null)
                    {
                        hg = this.Height;
                    }
                    this.Height = MaximumSize.Height;
                    this.Top = 0;
                    int c = this.Left;
                    for (int i = c; i > SW - this.Width; i -= 15)
                    {
                        this.Left = i;
                    }
                    this.Left = SW - this.Width;
                    break;
                //执行下移特效
                case AnchorStyles.Top:
                    int a = this.Top;
                    for (int i = a; i < 0; i += 15)
                    {
                        this.Top = i;
                    }
                    this.Top = 0;
                    break;
            }
            //hg不为空的话，恢复成原来高度
            if (hg != null && this.Left > 0 && this.Left < Screen.PrimaryScreen.Bounds.Width - this.Width)
            {
                this.Height = (int)hg;
                hg = null;
            }
        }

        #endregion

        #region 查找用户、群、最近联系人

        private void btnSearch_Click(object sender, EventArgs e)
        {
            txtSearch.Text = string.Empty;
            txtSearch_TextChanged(txtSearch, null);
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSearch.Text))
            {
                SearchShow.Items.Clear();
                SearchShow.Visible = false;
                btnSearch.Image = (Image)new System.ComponentModel.ComponentResourceManager(typeof(FrmMain))
                 .GetObject("btnSearch.Image");
                return;
            }

            SearchShow.Items.Clear();
            btnSearch.Image = Resources.main_search_deldown;

            if (ChatShow.Items.Count > 0)
            {
                //显示的是组织架构
                List<ChatTreeSubItem> treeItemList = ChatShow.GetSubItemsByDisplayName(txtSearch.Text.Trim());

                List<ChatTreeSubItem> items = new List<ChatTreeSubItem>();
                treeItemList.ForEach(x => { if (!items.Exists(y => { return y.DisplayName.Trim() == x.DisplayName.Trim(); })) items.Add(x); });

                List<ChatListSubItem> chatItemList = ChatShow.ChatTreeSubItemToChatListSubItem(items);
                ChatListItem chatItem = new ChatListItem("组织架构搜索结果");
                chatItem.IsOpen = true;
                chatItem.SubItems.AddRange(chatItemList.ToArray());
                SearchShow.Items.Add(chatItem);
            }

            //显示的是群聊列表
            List<ChatListSubItem> groupItemList = GroupShow.GetSubItemsByDisplayName(txtSearch.Text.Trim());
            ChatListItem groupItem = new ChatListItem("群搜索结果");
            groupItem.IsOpen = true;
            groupItem.SubItems.AddRange(groupItemList.ToArray());
            SearchShow.Items.Add(groupItem);

            SearchShow.Visible = true;
        }

        #endregion

        #region 打开与关闭最近菜单组

        private void toolStripBtnFriend_ButtonClick(object sender, EventArgs e)
        {
            ChatShow.Visible = true;
            GroupShow.Visible = false;
            RecentShow.Visible = false;

            ChatShow.Tag = true;
            GroupShow.Tag = false;
            RecentShow.Tag = false;
            SearchShow.Visible = false;

            GroupShow.Focus();
        }


        private void toolStripBtnGroup_ButtonClick(object sender, EventArgs e)
        {
            ChatShow.Visible = false;
            GroupShow.Visible = true;
            RecentShow.Visible = false;
            SearchShow.Visible = false;

            ChatShow.Tag = false;
            GroupShow.Tag = true;
            RecentShow.Tag = false;

            GroupShow.Focus();
        }

        private void toolStripBtnRecently_ButtonClick(object sender, EventArgs e)
        {
            ChatShow.Visible = false;
            GroupShow.Visible = false;
            RecentShow.Visible = true;
            SearchShow.Visible = false;

            ChatShow.Tag = false;
            GroupShow.Tag = false;
            RecentShow.Tag = true;

            RecentShow.Focus();
        }

        #endregion

        #region 打开聊天窗口

        //双击组织架构
        private void chatShow_DoubleClickSubItem(object sender, ChatTreeEventArgs e)
        {
            ChatTreeSubItem item = e.SelectSubItem;
            item.IsTwinkle = false;

            if (item.ID == m_CurrentUser.UserId)
                return;

            IChat chat = EngineContext.Current.ChatManager[item.ID];

            if (chat != null)
            {
                chat.Show();
                chat.Activate();
            }
            else
            {
                FriendInfo friendInfo = new FriendInfo()
                {
                    userInfoId = item.ID.ToString(),
                    loginName = item.DisplayName,
                    nickname = item.NicName
                };

                FrmChat fChat = new FrmChat(friendInfo);
                EngineContext.Current.ChatManager.AddChat(item.ID, fChat);
                fChat.Text = "与 " + friendInfo.loginName + " 对话中";
                fChat.Show();
            }
        }

        /// <summary>
        /// 双击群
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GroupShow_DoubleClickSubItem(object sender, ChatListEventArgs e)
        {
            ChatListSubItem item = e.SelectSubItem;
            item.IsTwinkle = false;

            item.UnReadCount = 0;

            ShowFrmGroup(item);
        }

        /// <summary>
        /// 双击最近联系人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RecentShow_DoubleClickSubItem(object sender, ChatListEventArgs e)
        {
            ChatListSubItem item = e.SelectSubItem;
            item.IsTwinkle = false;

            if (item.ID == m_CurrentUser.UserId)
                return;

            if (item.ChatType == ChatType.User)
            {
                ShowFrmChat(item);
            }
            else if (item.ChatType == ChatType.Group)
            {
                ShowFrmGroup(item);
            }
        }

        /// <summary>
        /// 双击搜索结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchShow_DoubleClickSubItem(object sender, ChatListEventArgs e)
        {
            ChatListSubItem item = e.SelectSubItem;
            item.IsTwinkle = false;

            if (item.ID == m_CurrentUser.UserId)
                return;

            if (item.ChatType == ChatType.User)
            {
                ShowFrmChat(item);
            }
            else if (item.ChatType == ChatType.Group)
            {
                ShowFrmGroup(item);
            }
        }

        /// <summary>
        /// 显示私聊
        /// </summary>
        /// <param name="item"></param>
        public static void ShowFrmChat(ChatListSubItem item)
        {
            IChat chat = EngineContext.Current.ChatManager[item.ID];

            if (chat != null)
            {
                chat.Show();
                chat.Activate();
            }
            else
            {
                FriendInfo friendInfo = new FriendInfo()
                {
                    userInfoId = item.ID.ToString(),
                    loginName = item.DisplayName,
                    nickname = item.NicName
                };

                FrmChat fChat = new FrmChat(friendInfo);
                EngineContext.Current.ChatManager.AddChat(item.ID, fChat);
                fChat.Text = "与 " + friendInfo.loginName + " 对话中";
                fChat.Show();
            }
        }

        /// <summary>
        /// 显示群聊
        /// </summary>
        /// <param name="item"></param>
        public static void ShowFrmGroup(ChatListSubItem item)
        {
            IChat chat = EngineContext.Current.ChatManager[item.ID];

            if (chat != null)
            {
                chat.Show();
                chat.Activate();
            }
            else
            {
                GroupInfo groupInfo = new GroupInfo()
                {
                    groupId = item.ID,
                    groupName = item.DisplayName,
                    groupDesc = item.PersonalMsg
                };

                FrmGroup fGroup = new FrmGroup(groupInfo);
                EngineContext.Current.ChatManager.AddChat(item.ID, fGroup);
                fGroup.Text = "与 " + item.DisplayName + " 群中";
                fGroup.Show();
            }
        }

        #endregion

        #region 点击组织架构节点加载子节点

        private void ClickTreeNode(ChatTreeItem item)
        {
            item.IsRequesting = true;
            OrganizeNode note = item.Data as OrganizeNode;
            if (note == null) return;

            bool error = false;
            AsyncClient.AsyncCall<OrganizeInfo>(() =>
            {
                return ServiceUrlProxy.GetInstance().GetOrganizeChildNode(note.subDeptNodeUrl, out error);
            },
            (organizeInfo) =>
            {
                if (organizeInfo == null)
                {
                    item.IsRequesting = false;
                }
                else
                {
                    item.IsRequestOK = true;

                    if (organizeInfo.deptNodes != null || organizeInfo.deptNodes.Count > 0)
                    {
                        foreach (OrganizeNode node in organizeInfo.deptNodes)
                        {
                            ChatTreeItem root = new ChatTreeItem(node.dept.deptName);
                            root.Data = node;
                            root.IsOpen = false;
                            item.Items.Add(root);
                        }
                    }

                    if (note.level > 1 && organizeInfo.users != null && organizeInfo.users.Count > 0)
                    {
                        foreach (OrganizeUser user in organizeInfo.users)
                        {
                            ChatTreeSubItem subItem = new ChatTreeSubItem();
                            subItem.HeadImage = Image.FromFile(GroupChat2013.Common.Helper.CombinePath(@"head\1.png"));

                            subItem.ID = user.userInfoId;
                            subItem.DisplayName = user.loginName;
                            subItem.NicName = user.name;
                            subItem.ChatType = ChatType.User;
                            if (user.online)
                                subItem.Status = ChatTreeSubItem.UserStatus.Online;
                            else
                                subItem.Status = ChatTreeSubItem.UserStatus.OffLine;
                            item.SubItems.AddAccordingToStatus(subItem);
                        }
                    }
                }
            });
        }

        public void UpdateUserStatus(string userId, CCWin.SkinControl.ChatTreeSubItem.UserStatus userStatus)
        {
            List<ChatTreeSubItem> list = ChatShow.GetSubItemsByID(userId);
            if (list != null && list.Count > 0)
            {
                list.ForEach(x =>
                {
                    x.Status = userStatus;
                });

                ChatShow.Update();
            }
        }

        #endregion

        #region 窗口事件

        //窗体关闭时
        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (ExistedHandle != null)
                ExistedHandle();

            System.Environment.Exit(0);
        }

        //QQ主菜单悬浮时
        private void toolQQMenu_MouseEnter(object sender, EventArgs e)
        {
            toolQQMenu.Image = Properties.Resources.menu_btn_highlight;
        }

        //QQ主菜单离开时
        private void toolQQMenu_MouseLeave(object sender, EventArgs e)
        {
            if (!QQMenu.Visible)
            {
                toolQQMenu.Image = Properties.Resources.menu_btn_normal;
            }
        }

        //打开QQ主菜单
        private void toolQQMenu_Click(object sender, EventArgs e)
        {
            QQMenu.Show(SkToolCdTwo, new Point(3, -2), ToolStripDropDownDirection.AboveRight);
            toolQQMenu.Image = Properties.Resources.menu_btn_highlight;
            toolQQMenu.Checked = true;
        }

        //QQ主菜单关闭时
        private void QQMenu_Closing(object sender, ToolStripDropDownClosingEventArgs e)
        {
            toolQQMenu.Image = Properties.Resources.menu_btn_normal;
            toolQQMenu.Checked = false;
        }

        //窗体重绘时
        private void FrmMain_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            SolidBrush sb = new SolidBrush(Color.FromArgb(100, 255, 255, 255));
            g.FillRectangle(sb, new Rectangle(new Point(1, Height - 60), new Size(Width - 2, 60)));
        }

        //窗体大小改变时
        private void FrmMain_SizeChanged(object sender, EventArgs e)
        {

        }

        private void FrmMain_DragDrop(object sender, DragEventArgs e)
        {
            BackLayout = true;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void stmiServerConfig_Click(object sender, EventArgs e)
        {
            FrmServiceConfig frmConfig = new FrmServiceConfig();
            frmConfig.Show();
        }

        private void stmiNotceFormConfig_Click(object sender, EventArgs e)
        {
            FrmClientConfig frmConfig = new FrmClientConfig();
            frmConfig.Show();
        }

        private void tsmGroupManager_Click(object sender, EventArgs e)
        {
            FrmGroupManager gfm = new FrmGroupManager();
            gfm.Show();
        }

        private void tsmGroupManager2_Click(object sender, EventArgs e)
        {
            FrmGroupManager gfm = new FrmGroupManager();
            gfm.Show();
        }

        private void tsmiSetPassword_Click(object sender, EventArgs e)
        {
            FrmResetPassword frp = new FrmResetPassword(m_CurrentUser);
            frp.ShowDialog();
        }

        private void FrmMain_MouseEnter(object sender, EventArgs e)
        {
            timHide.Start();
        }

        ///// <summary>
        ///// 群空间
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void GroupAppToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    ChatListSubItem item = GroupShow.SelectSubItem;
        //    if (item != null)
        //    {
        //        string url = ServiceUrlProxy.GetInstance().GroupZOOMURL(m_CurrentUser.UserName, m_CurrentUser.CID, item.ID);
        //        FrmGroup.OpenWithChrome(url);
        //    }
        //}

        ///// <summary>
        ///// 共享文件
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void ShareToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    ChatListSubItem item = GroupShow.SelectSubItem;
        //    if (item != null)
        //    {
        //        string url = ServiceUrlProxy.GetInstance().GroupFileShareURL(m_CurrentUser.UserName, m_CurrentUser.CID, item.ID);
        //        FrmGroup.OpenWithChrome(url);
        //    }
        //}

        ///// <summary>
        ///// 群交流记录
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void GroupChatRecordToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    ChatListSubItem item = GroupShow.SelectSubItem;
        //    if (item != null)
        //    {
        //        string url = ServiceUrlProxy.GetInstance().GroupChatMsgURL(m_CurrentUser.UserName, m_CurrentUser.CID, item.ID);
        //        FrmGroup.OpenWithChrome(url);
        //    }
        //}

        private void lblQm_Click(object sender, EventArgs e)
        {
            if (m_AnnounceConfigInfo == null || string.IsNullOrEmpty(m_AnnounceConfigInfo.showAnnounce))
                return;

            FrmMessage fm = new FrmMessage("通知",
                    m_AnnounceConfigInfo.showAnnounce, m_AnnounceConfigInfo.url);

            fm.ShowDialog();
        }

        #endregion

        #region 群气泡提示

        public void NotifyGroupHasNewMsg(string groupId, int unReadCount)
        {
            if (groupItem.SubItems != null && groupItem.SubItems.Count > 0)
            {
                foreach (ChatListSubItem item in groupItem.SubItems)
                {
                    if (item.ID == groupId)
                    {
                        item.UnReadCount = unReadCount;
                        GroupShow.Refresh();
                        return;
                    }
                }
            }
        }

        #endregion

        #region 设置群消息接收类型

        /// <summary>
        /// 闪烁提示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiTwinkleType_Click(object sender, EventArgs e)
        {
            ChatListSubItem item = GroupShow.SelectSubItem;
            if (item != null)
            {
                GroupNotifyRepository groupNotify = new GroupNotifyRepository(EngineContext.Current.FilePathManager.DbPath);
                groupNotify.DeleteGroup(item.ID);

                tsmiBubbleType.Checked = false;
                tsmiTwinkleType.Checked = true;
            }
        }

        /// <summary>
        /// 气泡提示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiBubbleType_Click(object sender, EventArgs e)
        {
            ChatListSubItem item = GroupShow.SelectSubItem;
            if (item != null)
            {
                GroupNotifyRepository groupNotify = new GroupNotifyRepository(EngineContext.Current.FilePathManager.DbPath);
                groupNotify.AddBubbleNotifyGroup(item.ID);

                tsmiBubbleType.Checked = true;
                tsmiTwinkleType.Checked = false;
            }
        }

        private void GroupingMenu_Opened(object sender, EventArgs e)
        {
            ChatListSubItem item = GroupShow.SelectSubItem;
            if (item != null)
            {
                GroupNotifyRepository groupNotify = new GroupNotifyRepository(EngineContext.Current.FilePathManager.DbPath);
                if (groupNotify.IsExistGroup(item.ID))
                {
                    tsmiBubbleType.Checked = true;
                    tsmiTwinkleType.Checked = false;
                }
                else
                {
                    tsmiBubbleType.Checked = false;
                    tsmiTwinkleType.Checked = true;
                }
            }
        }

        #endregion

        #region 提示有离线消息

        public void SetHasReadMsg()
        {
            foreach (ToolStripButton item in this.skinToolBusBtn.Items)
            {
                if (item.Name == ConstClass.appUnRead)
                {
                    item.Image = Resources.hasUnreadMsg;

                    skinToolBusBtn.Update();
                    return;
                }
            }
        }

        public void SetUnReadMsg()
        {
            foreach (ToolStripButton item in this.skinToolBusBtn.Items)
            {
                if (item.Name == ConstClass.appUnRead)
                {
                    item.Image = Resources.messagebox1;

                    skinToolBusBtn.Update();
                    return;
                }
            }
        }

        public ButtonConfigInfo GetHasReadButtonData()
        {
            ButtonConfigInfo configInfo = null;
            foreach (ToolStripButton item in this.skinToolBusBtn.Items)
            {
                if (item.Name == ConstClass.appUnRead)
                {
                    configInfo = item.Tag as ButtonConfigInfo;
                    break;
                }
            }

            return configInfo;
        }

        #endregion

        #region 设置右键群弹出的菜单

        public void InitGroupMenu()
        {
            AsyncClient.AsyncCall<List<ButtonConfigInfo>>(() =>
            {
                GroupButtonConfigParse appConfigParse = new GroupButtonConfigParse();
                return appConfigParse.Parse();
            },
            (configInfoList) =>
            {
                List<ToolStripItem> items = new List<ToolStripItem>();

                for (int i = 0; i < configInfoList.Count; i++)
                {
                    string name = "tsmenuitem" + i;
                    items.Add(CreateToolStripMenuItem(configInfoList[i], name));
                }

                items.Add(this.GroupingMenu.Items[0]);
                items.Add(this.GroupingMenu.Items[1]);
                this.GroupingMenu.Items.Clear();
                this.GroupingMenu.Items.AddRange(items.ToArray());
            });
        }

        private ToolStripItem CreateToolStripMenuItem(ButtonConfigInfo configInfo, string name)
        {
            ToolStripMenuItem menuItem = new ToolStripMenuItem();
            menuItem.Name = name;
            menuItem.Size = new System.Drawing.Size(146, 22);
            menuItem.Text = configInfo.tip;
            menuItem.ToolTipText = configInfo.tip;

            menuItem.Click += (s, e) =>
            {
                ChatListSubItem item = GroupShow.SelectSubItem;
                string gname = HttpUtility.UrlEncode(item.DisplayName);

                string url = string.Format("{0}?cid={1}&gId={2}&gName={3}"
                     , configInfo.link, m_CurrentUser.CID, item.ID, gname);

                FrmGroup.OpenWithChrome(url);
            };

            return menuItem;
        }

        #endregion
    }
}